const std = @import("std");
const glfw = @import("zglfw");
const zopengl = @import("zopengl");

const zemscripten = @import("zemscripten");
pub const panic = zemscripten.panic;

pub const std_options = std.Options{
    .logFn = zemscripten.log,
};

const minimal_glfw_gl = @import("minimal_glfw_gl.zig");

const gl_es_version_major: u16 = 2;
const gl_es_version_minor: u16 = 0;

export fn main() c_int {
    init() catch |err| {
        std.log.err("Initialization failed with error: {s}", .{@errorName(err)});
        return -1;
    };

    return 0;
}

export fn mainLoopCallback() void {
    minimal_glfw_gl.updateAndRender();
}
fn loadopengl() !void {
    // try zopengl.loadCoreProfile(glfw.getProcAddress, 4, 0);
    try zopengl.loadEsProfile(glfw.getProcAddress, 2, 0);
    // return;
}
// var arena: std.heap.ArenaAllocator = std.heap.ArenaAllocator.init(std.heap.page_allocator);
// defer arena.deinit();
// const allocator = arena.allocator();
const allocator = std.heap.c_allocator;
fn init() !void {
    try glfw.init();

    glfw.windowHint(.client_api, .opengl_es_api);
    glfw.windowHint(.opengl_profile, .opengl_core_profile);

    glfw.windowHint(.context_version_major, gl_es_version_major);
    glfw.windowHint(.context_version_minor, gl_es_version_minor);
    glfw.windowHint(.doublebuffer, true);

    // glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // We don't want the old OpenGL
    // glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    // glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
    // glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);

    // var arena: std.heap.ArenaAllocator = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    // // defer arena.deinit();
    // const allocator = arena.allocator();
    // std.heap.c_allocator
    try minimal_glfw_gl.init(allocator, loadopengl);
    // try zopengl.loadEsProfile(glfw.getProcAddress, gl_es_version_major, gl_es_version_minor);
    // zemscripten.setMainLoop(mainLoopCallback, 0, true);

    zemscripten.setMainLoop(mainLoopCallback, null, false);
}
